package main

import (
	"os"
	"path/filepath"
	"strings"
	"path"
	"fmt"
	"io/ioutil"
	"strconv"
)

var BasePath = ""
func main() {

	if len(os.Args) >= 2 {

		fp := BasePath + string(os.PathSeparator) + "texts" + string(os.PathSeparator) + os.Args[1]


		dp := BasePath + string(os.PathSeparator) + "html" + string(os.PathSeparator) + strings.TrimSuffix(os.Args[1], path.Ext(fp))


		CreateDir(dp)

		b,err := ioutil.ReadFile(fp);

		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		text := string(b)

		texts := strings.Split(text,"<h2>")

		for index,item := range texts {

			p := dp + string(os.PathSeparator) + strconv.Itoa(index) + ".html"
			article := strings.Split(item,"</h2>")

			if len(article) >= 2 {

				title := article[0]
				content := "<p>" + strings.Replace(article[1],"\r","</p><p>",-1) + "</p>"

				html := `<!DOCTYPE html>
<html  lang="en">
<head>
    <meta charset="UTF-8">
    <title>`+ title +`</title>
    <link href="../Styles/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2>` + title + ` </h2> `+ content +`
</body>
</html>`

				if err = ioutil.WriteFile(p,[]byte(html),0777);err != nil {
					fmt.Println("创建文件错误：", err)
				}

			}
		}
	}
}

func init()  {
	if dir,err := filepath.Abs(filepath.Dir(os.Args[0]));err == nil {
		BasePath = dir
	}
}

func CreateDir(d string)  {
	if err := os.MkdirAll(d,0777); err != nil {
		fmt.Println("创建目录错误：",err)
		os.Exit(1)
	}
}